<?php

namespace app\admin\controller;

use app\common\model\UserIncome;
use think\Controller;
use think\Db;
use think\facade\Request;
use think\Loader;
use \app\admin\model\FakeData as FakeDataModel;

class FakeData extends Controller
{

    protected $middleware = [
        'app\http\middleware\checkAdminToken::class'
    ];

    //列表页
    public function index()
    {
        $p = Request::param('p', 10);
        $fakedata = FakeDataModel::limit($p)
            ->where('vip', 1)
            ->order('money', 'desc')
            ->select();
        $fakedata_vip = UserIncome::  join('user', 'user_income.user_id=user.id')
            ->where([
                ['user.vip', '=', 1],
            ])->field('user.id as inid,user.username, user.avatar,sum(user_income.money) as money,user_income.mini_app_code,user_income.user_id')
            ->order('user_income.money', 'desc')
            ->group('user_id')
            ->limit(10)
            ->select();
        $setting = Db::table('setting')->where('name', 'is_real')->find();

        $result['is_real'] = $setting['data'] == 0 ? 0:1;
        $result['list'] = $setting['data'] == 0 ? $fakedata : $fakedata_vip;

        $this->result($result, 200, '请求成功');
    }

    public function show()
    {
        $id = Request::param('id');
        $fakedata = FakeDataModel::get($id);
        $this->result($fakedata,200,'请求成功');
    }

    public function update(\think\Request $request)
    {
        //
        $id = Request::param('id', 0);
        $user = model('FakeData');

        $result = $this->validate(
            $request->param(),
            [
                'avatar|头像'  => 'require|max:255',
                'username|用户名'   => 'require',
                'money|金额'   => 'float',
            ]);
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->result('', 200, $result);
        }

        $result = $user -> allowField(['avatar','username','money'])->save($request->param(),['id'=>$id]);
        if ($result) {
            $this->result('', 200, '更新成功');
        }
    }


    public function delete($id)
    {
        //
    }
}
